package com.joplus.housekeeper.utils;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ListView 万能适配器
 *
 * @param <T>
 * @author tangdehao
 */
public abstract class CommonAdapter<T> extends BaseAdapter {

    protected Context context;
    protected List<T> datas;
    private int layoutId;


    Boolean isShowAnimation = true;

    public void setShowAnimation(Boolean showAnimation) {
        isShowAnimation = showAnimation;
    }

    /**
     * @param context  上下文
     * @param datas    数据
     * @param layoutId 布局id
     */
    public CommonAdapter(Context context, int layoutId, List<T> datas) {
        this.context = context;
        this.datas = datas;
        this.layoutId = layoutId;
        this.isFrist = new HashMap<Integer, Boolean>();

    }

    @Override
    public int getCount() {
        if (datas == null) {
            return 0;
        } else {
            return datas.size();
        }

    }

    @Override
    public T getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = ViewHolder.get(context, convertView, parent,
                layoutId, position);
        convert(viewHolder, getItem(position));

        if (isFrist.get(position) == null || isFrist.get(position)) {
            isFrist.put(position, false);

            if (isShowAnimation) {
                AnimationSet set = new AnimationSet(false);
                Animation animation = new TranslateAnimation(0, 0, 300, 0);
                animation.setDuration(600);
                set.addAnimation(animation);
                viewHolder.getConvertView().startAnimation(set);
            }


        }
        return viewHolder.getConvertView();
    }

    public abstract void convert(ViewHolder holder, T t);


    private Map<Integer, Boolean> isFrist;
}
